<?php
declare (strict_types = 1);

namespace app\admin\controller;
use think\Request;
class Admin extends AdminBase
{
    protected function initialize()
    {
        parent::initialize();
        $this->model = new \app\auth\model\Admin;
        $this->validate = new \app\auth\validate\Admin;
    }
    // 设置搜索条件
    protected function searchConditionHandle(&$where)
    {
        $search = $this->request->param('search',null);
        if($search) {
            $search = json_decode($search, true);
            if(is_array($search) && sizeof($search) > 0) {
                if(array_key_exists('field', $search) && !empty($search['field'])){
                    ((array_key_exists('keyword', $search) && !empty($search['keyword'])) && $where[] = [$search['field'], 'like', '%'.$search['keyword'].'%']);
                } else {
                    ((array_key_exists('keyword', $search) && !empty($search['keyword'])) && $where[] = ['name|value|scope|remark','like', '%'.$search['keyword'].'%']);
                }
            }
        }
    }
    /**
     * 添加新数据
     *
     * @return void
     */
    public function save(Request $request){
        $data = $request->post();
        $data['author_id'] = $this->admin_id;
        if(!$this->validate->scene('create')->check($data)){
            return json($this->validate->getError(),500);
        }else {
            $this->model->strict(false)->insert($data);
            return json('新增成功！');
        }
    }
    /**
     * 更新数据
     *
     * @return void
     */
    public function update(Request $request, $id) {
        $data = $request->post();
        unset($data['update_time']);unset($data['create_time']);
        if(!$this->validate->scene('update')->check($data)){
            return json($this->validate->getError(),500);
        }else {
            $this->model->where($this->model->getPk(),$id)->update($data);
            return json('数据更新成功！');
        }
    }
}
